<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="160px"
      v-loading="formLoading"
    >
      <el-form-item v-if="false" :label="t('opticore.bomplcrel.form.bomId')" prop="bomId">
        <el-input v-model="formData.bomId" />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.itemCode')" prop="itemCode">
        <el-autocomplete
          v-model="formData.itemCode"
          :fetch-suggestions="querySearchAsync"
          :placeholder="t('opticore.bomplcrel.form.itemCodePlaceholder')"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.itemName')" prop="itemName">
        <el-input
          v-model="formData.itemName"
          :placeholder="t('opticore.bomplcrel.form.autoFill')"
          :readonly="true"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item
        :label="t('opticore.bomplcrel.form.itemSpecification')"
        prop="itemSpecification"
      >
        <el-input
          v-model="formData.itemSpecification"
          :placeholder="t('opticore.bomplcrel.form.autoFill')"
          :readonly="true"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.itemDesc')" prop="itemDesc">
        <el-input
          v-model="formData.itemDesc"
          :placeholder="t('opticore.bomplcrel.form.autoFill')"
          :readonly="true"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.drawingNo')" prop="drawingNo">
        <el-input
          v-model="formData.drawingNo"
          :placeholder="t('opticore.bomplcrel.form.autoFill')"
          :readonly="true"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.mateType')" prop="mateType">
        <el-input
          :value="mateTypeLabel"
          :placeholder="t('opticore.bomplcrel.form.autoFill')"
          :readonly="true"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.unitName')" prop="unitName">
        <el-input
          v-model="formData.unitName"
          :placeholder="t('opticore.bomplcrel.form.autoFill')"
          :readonly="true"
          :disabled="true"
        />
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.routeId')" prop="routeId">
        <!-- <el-autocomplete
          v-model="formData.routeName"
          :fetch-suggestions="querySearchRouteAsync"
          :placeholder="t('opticore.bomplcrel.form.routeCodePlaceholder')"
          @select="handleRouteSelect"
        /> -->
        <el-select
            v-model="formData.routeId"
          filterable
          clearable
          style="width: 100%"
         :placeholder="t('opticore.bomplcrel.form.routeCodePlaceholder')"
        
        >
          <el-option
            v-for="(item,i) in routeList.list"
            :key="i"
            :label="item.routeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('opticore.bomplcrel.form.quantity')" prop="quantity">
        <el-input
          v-model="formData.quantity"
          :placeholder="t('opticore.bomplcrel.form.quantityPlaceholder')"
          @input="validateQuantity"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading || !itemInfoLoaded">
        {{ t('common.button.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.button.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { BomPlcRelApi, BomPlcRelVO } from '@/api/opticore/bomplcrel'
import { BomListPlcApi } from '@/api/opticore/bomlistplc'
import { handleTree } from '@/utils/tree'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { RouteApi } from '@/api/opticore/route'

/** 产品 表单 */
defineOptions({ name: 'BomPlcRelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const itemInfoLoaded = ref(false) // 物料信息是否已加载
const itemRouteInfoLoaded = ref(false) // 工艺路线信息是否已加载
interface Material {
  itemCode: string
  itemName: string
}

const materialList = ref<{ list: Material[] }>({
  list: []
}) // 所有物料信息列表
const materialLoading = ref(false) // 物料列表加载状态

interface Route {
  routeCode: string
  routeName: string
  routeId: number
}

const routeList = ref<{ list: Route[] }>({
  list: []
}) // 所有物料信息列表
const routeLoading = ref(false) // 物料列表加载状态

const formData = ref({
  itemCode: undefined,
  itemName: undefined,
  itemSpecification: undefined,
  itemDesc: undefined,
  drawingNo: undefined,
  mateType: undefined,
  unitName: undefined,
  routeId: undefined,
  routeCode: undefined,
  routeName: undefined,
  quantity: undefined,
  bomId: undefined,
  parentId: undefined
})

const formRules = reactive({
  itemCode: [{ required: true, message: '请输入物料号', trigger: 'blur' }],
  // routeId: [{ required: true, message: '请输入工艺路线', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
})

 

// 限制 quantity 只能输入数字
const validateQuantity = (value) => {
  // 移除除数字和小数点之外的所有字符
  let validValue = value.replace(/[^0-9.]/g, '')
  // 处理多个小数点的情况，只保留第一个
  const decimalIndex = validValue.indexOf('.')
  if (decimalIndex !== -1) {
    validValue =
      validValue.substring(0, decimalIndex + 1) +
      validValue.substring(decimalIndex + 1).replace(/\./g, '')
  }
  // 更新表单数据
  if (value !== validValue) {
    formData.value.quantity = validValue
  }
}

const formRef = ref() // 表单 Ref
const bomPlcRelTree = ref() // 树形结构

/** 打开弹窗 */
const open = async (type: string, parent_id: number, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  formData.value.parentId = parent_id
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BomPlcRelApi.getBomPlcRel(id)
      itemInfoLoaded.value = true
      itemRouteInfoLoaded.value = true
    } finally {
      formLoading.value = false
      itemRouteInfoLoaded.value = false
    }
  }
  await getBomPlcRelTree()
  // 确保物料列表已加载
  if (materialList.value.list.length === 0) {
    await loadMaterialList()
  }
  if (routeList.value.list.length === 0) {
    await loadRouteList()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 加载工艺路线列表 */
const loadRouteList = async () => {
  if (routeList.value.list.length > 0) return // 已经加载过则不再加载
  routeLoading.value = true
  try {
    // 这里使用不分页的接口获取所有工艺路线
    const params = {
      pageNo: 1,
      pageSize: 9999
    }
    const data = await RouteApi.getRoutePage(params)
    
    routeList.value = data || []

    console.log(999,routeList.value);
    
  } catch (error) {
    console.error('加载工艺路线列表失败', error)
    message.error(t('加载工艺路线列表失败，请重试'))
  } finally {
    routeLoading.value = false
  }
}

/** 加载物料列表 */
const loadMaterialList = async () => {
  if (materialList.value.list.length > 0) return // 已经加载过则不再加载
  materialLoading.value = true
  try {
    // 这里使用不分页的接口获取所有物料信息
    const params = {
      pageNo: 1,
      pageSize: 9999
    }
    const data = await BomListPlcApi.getBomListPlcPage(params)
    materialList.value = data || []
  } catch (error) {
    console.error('加载物料列表失败', error)
    message.error(t('加载物料列表失败，请重试'))
  } finally {
    materialLoading.value = false
  }
}

/** 获取物料类型标签 */
const mateTypeLabel = computed(() => {
  const mateTypeCode = formData.value.mateType
  const dict = getStrDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE) // 获取字典数据
  const dictItem = dict.find((item) => item.value === mateTypeCode)
  return dictItem ? dictItem.label : '' // 如果找不到对应项，返回空字符串
})

/** 模糊搜索物料 */
const querySearchAsync = (queryString: string, callback: Function) => {
  if (!queryString) {
    callback([])
    return
  }
  const results = materialList.value.list
    .filter((item) => item.itemCode?.includes(queryString))
    .map((item) => ({
      value: item.itemCode + ' ' + item.itemName,
      ...item
    }))

  callback(results)
}

/** 模糊搜索工艺路线 */
const querySearchRouteAsync = (queryString: string, callback: Function) => {
  if (!queryString) {
    callback([])
    return
  }
  const results = routeList.value.list
    .filter((item) => item.routeName?.includes(queryString))
    .map((item) => ({
      value: item.routeCode + ' ' + item.routeName,
      ...item
    }))
  callback(results)
}

/** 处理物料选择 */
const handleSelect = (item: any) => {
  // 填充物料信息
  formData.value.bomId = item.id
  formData.value.itemCode = item.itemCode
  formData.value.itemName = item.itemName
  formData.value.itemSpecification = item.itemSpecification
  formData.value.itemDesc = item.itemDesc
  formData.value.drawingNo = item.drawingNo
  formData.value.mateType = item.mateType
  formData.value.unitName = item.unitName
  itemInfoLoaded.value = true
}

/** 处理工艺路线选择 */
// const handleRouteSelect = (item: any) => {
//   // 填充物料信息
//   formData.value.routeCode = item.routeCode
//   formData.value.routeName = item.routeName
//   formData.value.routeId = item.id
//   itemRouteInfoLoaded.value = true
// }

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BomPlcRelVO
    if (formType.value === 'create') {
      await BomPlcRelApi.createBomPlcRel(data)
      message.success(t('common.createSuccess'))
    } else {
      await BomPlcRelApi.updateBomPlcRel(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    routeCode: undefined,
    itemCode: undefined,
    itemName: undefined,
    itemSpecification: undefined,
    itemDesc: undefined,
    drawingNo: undefined,
    mateType: undefined,
    unitName: undefined,
    routeId: undefined,
    quantity: undefined,
    bomId: undefined,
    parentId: undefined
  }
  formRef.value?.resetFields()
  itemInfoLoaded.value = false
  itemRouteInfoLoaded.value = false
}

/** 获得产品树 */
const getBomPlcRelTree = async () => {
  bomPlcRelTree.value = []
  const data = await BomPlcRelApi.getBomPlcRelList()
  const root: Tree = { id: 0, name: '顶级产品', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  bomPlcRelTree.value.push(root)
}

// 组件初始化时加载物料列表
loadMaterialList()
loadRouteList()
</script>
